package com.android.hidephotosplus.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.hidephotosplus.R;
import com.android.hidephotosplus.model.ModelMedia;
import com.android.hidephotosplus.util.BitmapUtils;
import com.android.hidephotosplus.util.Config;
import com.android.hidephotosplus.util.MLoadMedia;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class ViewMediaAdapter extends PagerAdapter implements
		OnPhotoTapListener, OnClickListener {

	private Context context;

	private ArrayList<ModelMedia> arrMedias;

	private DisplayImageOptions options;

	private ImageLoader imageLoader;

	private Gallery mGallery;

	private boolean isShowGallery = false;

	private boolean isPublic;

	private LinearLayout mLinearActionMode;

	private Timer mTimer;

	public ViewMediaAdapter(Context context, ArrayList<ModelMedia> arrMedias,
			Gallery mGallery, boolean isPublic, LinearLayout linearActionMode,
			Timer timer) {
		this.context = context;
		this.arrMedias = arrMedias;
		this.mGallery = mGallery;
		this.isPublic = isPublic;
		this.mLinearActionMode = linearActionMode;
		this.mTimer = timer;

		isShowGallery = false;

		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));

		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_images_default)
				.showImageOnFail(R.drawable.ic_images_default)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public int getCount() {
		return arrMedias.size();
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	@Override
	public Object instantiateItem(ViewGroup container, final int position) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater
				.inflate(R.layout.item_view_pager, container, false);
		final PhotoView imageView = (PhotoView) view
				.findViewById(R.id.imageViewTouch);
		ImageView imagePlay = (ImageView) view.findViewById(R.id.imagePlay);
		imagePlay.setOnClickListener(this);
		imageView.setOnPhotoTapListener(this);
		imageView.setTag(position);
		final ProgressBar progressBar = (ProgressBar) view
				.findViewById(R.id.loading);
		final ImageView imageThumb = (ImageView) view
				.findViewById(R.id.imageThumbail);

		if (position != -1 && position < arrMedias.size()) {
			String pathMedia = null;
			boolean isVideo = arrMedias.get(position).isVideo();
			if (isPublic)
				pathMedia = arrMedias.get(position).getPathMediaStock();
			else
				pathMedia = arrMedias.get(position).getPathMediaHidden();

			if (pathMedia != null && !isVideo) {
				imagePlay.setVisibility(View.GONE);
				imageLoader.displayImage("file://" + pathMedia, imageView,
						options, new ImageLoadingListener() {
							@Override
							public void onLoadingStarted(String imageUri,
									View view) {
								progressBar.setVisibility(View.VISIBLE);
								imageThumb.setVisibility(View.VISIBLE);
								Bitmap bitmap = getBitmap(isPublic, position);
								if (bitmap != null)
									imageThumb.setImageBitmap(bitmap);
								else
									Log.e("bimap null", "bitmap null");

							}

							@Override
							public void onLoadingFailed(String imageUri,
									View view, FailReason failReason) {
							}

							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								progressBar.setVisibility(View.GONE);
								imageThumb.setVisibility(View.GONE);
							}

							@Override
							public void onLoadingCancelled(String imageUri,
									View view) {

							}
						});
			} else if (pathMedia != null && isVideo) {
				imagePlay.setVisibility(View.VISIBLE);
				imagePlay.setTag(pathMedia);
				Bitmap bitmap = BitmapUtils.createThumbnailVideos(pathMedia);
				if (bitmap != null)
					imageView.setImageBitmap(bitmap);
				else
					Log.e("null", "nul...");
			}

			((ViewPager) container).addView(view, 0);
		}
		return view;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view.equals(object);
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		((ViewPager) container).removeView((View) object);
	}

	@Override
	public void restoreState(Parcelable state, ClassLoader loader) {
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void startUpdate(View container) {
	}

	@Override
	public void onPhotoTap(View view, float x, float y) {
		mTimer.cancel();
		if (!isShowGallery) {
			mGallery.setVisibility(View.VISIBLE);
			mLinearActionMode.setVisibility(View.VISIBLE);
		} else {
			mGallery.setVisibility(View.GONE);
			mLinearActionMode.setVisibility(View.GONE);
		}
		isShowGallery = !isShowGallery;
	}

	Runnable mNotifyRunnable = new Runnable() {
		@Override
		public void run() {
			// notifyDataSetChanged();
		}
	};

	private Bitmap getBitmap(boolean isPublic, int position) {
		Bitmap bitmap = null;
		if (isPublic) {
			if (arrMedias.get(position).isVideo()) {
				try {
					bitmap = BitmapUtils.createThumbnailVideos(arrMedias.get(
							position).getPathMediaStock());
					return bitmap;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				try {
					bitmap = BitmapUtils.getThumbnailByPath(
							context.getContentResolver(),
							arrMedias.get(position).getPathMediaStock());
					return bitmap;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			if (arrMedias.get(position).isVideo()) {
				try {
					bitmap = BitmapUtils.createThumbnailVideos(arrMedias.get(
							position).getPathMediaStock());
					return bitmap;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				File thumb = new File(arrMedias.get(position)
						.getPathMediaHidden() + Config.EXETENSION_THUMBNAIL);
				if (thumb.exists())
					bitmap = BitmapUtils.getThumbFromDisk(
							arrMedias.get(position).getPathMediaHidden(),
							Config.MAX_PIXELS_WIDTH, Config.MAX_PIXELS_HEIGHT);
				// bitmap = BitmapUtils.decodeFile(
				// context.getContentResolver(),
				// arrMedias.get(position).getPathMediaHidden());
				return bitmap;
			}
		}
		return bitmap;

	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.imagePlay) {
			String pathMedia = (String) view.getTag();
			Intent in = new Intent(Intent.ACTION_VIEW);
			in.setDataAndType(Uri.parse(pathMedia), "video/*");
			try {
				context.startActivity(in);
			} catch (Exception e) {
				Toast.makeText(context,
						context.getString(R.string.cant_support_video),
						Toast.LENGTH_LONG).show();
			}
		}

	}

}
